<template>
  <div class="website-settings">
    <t-form :data="formData" :rules="rules" :label-width="120" @submit="handleSubmit">
      <t-divider>基本信息</t-divider>
      
      <t-form-item label="网站名称" name="siteName">
        <t-input v-model="formData.siteName" placeholder="请输入网站名称" />
      </t-form-item>
      
      <t-form-item label="网站标语" name="slogan">
        <t-input v-model="formData.slogan" placeholder="请输入网站标语" />
      </t-form-item>
      
      <t-form-item label="联系电话" name="contactPhone">
        <t-input v-model="formData.contactPhone" placeholder="请输入联系电话" />
      </t-form-item>
      
      <t-form-item label="联系邮箱" name="contactEmail">
        <t-input v-model="formData.contactEmail" placeholder="请输入联系邮箱" />
      </t-form-item>
      
      <t-form-item label="网站LOGO" name="logo">
        <t-upload
          v-model="formData.logo"
          action="/api/upload/image"
          theme="image"
          accept="image/*"
          :limit="1"
          :headers="{ Authorization: `Bearer ${token}` }"
          @success="handleLogoUploadSuccess"
        >
          <template #default>
            <div class="upload-trigger">
              <template v-if="formData.logoUrl">
                <img :src="formData.logoUrl" class="preview-image" />
              </template>
              <template v-else>
                <t-icon name="upload" size="24px" />
                <p>点击上传Logo</p>
              </template>
            </div>
          </template>
        </t-upload>
      </t-form-item>
      
      <t-form-item label="备案信息" name="icp">
        <t-input v-model="formData.icp" placeholder="请输入网站备案信息" />
      </t-form-item>
      
      <t-divider>SEO设置</t-divider>
      
      <t-form-item label="网站标题" name="title">
        <t-input v-model="formData.title" placeholder="请输入网站标题" />
      </t-form-item>
      
      <t-form-item label="网站关键词" name="keywords">
        <t-textarea
          v-model="formData.keywords"
          placeholder="请输入网站关键词，多个关键词用英文逗号分隔"
          :autosize="{ minRows: 2, maxRows: 4 }"
        />
      </t-form-item>
      
      <t-form-item label="网站描述" name="description">
        <t-textarea
          v-model="formData.description"
          placeholder="请输入网站描述"
          :autosize="{ minRows: 3, maxRows: 5 }"
        />
      </t-form-item>
      
      <t-divider>第三方设置</t-divider>
      
      <t-form-item label="百度统计代码" name="baiduAnalytics">
        <t-textarea
          v-model="formData.baiduAnalytics"
          placeholder="请输入百度统计代码"
          :autosize="{ minRows: 3, maxRows: 5 }"
        />
      </t-form-item>
      
      <t-form-item>
        <t-space>
          <t-button theme="primary" type="submit" :loading="submitLoading">保存设置</t-button>
          <t-button theme="default" variant="base" @click="resetForm">重置</t-button>
        </t-space>
      </t-form-item>
    </t-form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { MessagePlugin } from 'tdesign-vue-next'
import { useUserStore } from '@/stores/user'

// 获取用户Token
const userStore = useUserStore()
const token = userStore.token

// 表单数据
interface FormData {
  siteName: string;
  slogan: string;
  contactPhone: string;
  contactEmail: string;
  logo: any[];
  logoUrl: string;
  icp: string;
  title: string;
  keywords: string;
  description: string;
  baiduAnalytics: string;
  [key: string]: any;
}

const formData = reactive<FormData>({
  siteName: '',
  slogan: '',
  contactPhone: '',
  contactEmail: '',
  logo: [],
  logoUrl: '',
  icp: '',
  title: '',
  keywords: '',
  description: '',
  baiduAnalytics: ''
})

// 表单验证规则
const rules = {
  siteName: [{ required: true, message: '请输入网站名称', type: 'error' }],
  contactPhone: [{ pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号码', type: 'error', trigger: 'blur' }],
  contactEmail: [{ pattern: /^[\w-.]+@([\w-]+\.)+[\w-]{2,4}$/, message: '请输入正确的邮箱地址', type: 'error', trigger: 'blur' }]
}

// 提交状态
const submitLoading = ref(false)

// 获取网站设置
const fetchSettings = async () => {
  try {
    // 这里应该从API获取数据
    // const { data } = await getWebsiteSettings()
    
    // 模拟数据
    const data = {
      siteName: '贵州四季康养',
      slogan: '健康生活，快乐四季',
      contactPhone: '18888888888',
      contactEmail: 'contact@forurseans.com',
      logoUrl: 'https://example.com/logo.png',
      icp: '黔ICP备xxxxxxxx号',
      title: '贵州四季康养 - 健康生活平台',
      keywords: '康养,贵州,健康,旅游,度假',
      description: '贵州四季康养平台，提供优质的康养旅游、健康管理、度假服务。',
      baiduAnalytics: ''
    }
    
    // 填充表单数据
    if (data) {
      Object.keys(formData).forEach(key => {
        if (key in data) {
          formData[key] = data[key]
        }
      })
      
      // 设置logo预览
      if (data.logoUrl) {
        formData.logoUrl = data.logoUrl
      }
    }
  } catch (error) {
    console.error('获取网站设置失败', error)
    MessagePlugin.error('获取网站设置失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  submitLoading.value = true
  try {
    // 这里应该调用API保存数据
    // await updateWebsiteSettings(formData)
    
    // 模拟API调用延迟
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    MessagePlugin.success('保存成功')
  } catch (error) {
    console.error('保存网站设置失败', error)
    MessagePlugin.error('保存网站设置失败')
  } finally {
    submitLoading.value = false
  }
}

// 重置表单
const resetForm = () => {
  fetchSettings()
}

// Logo上传成功回调
const handleLogoUploadSuccess = (context: any) => {
  if (context.results?.[0]?.response?.url) {
    formData.logoUrl = context.results[0].response.url
  }
}

// 初始化
onMounted(() => {
  fetchSettings()
})
</script>

<style scoped>
.website-settings {
  padding: 20px 0;
}

.upload-trigger {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 180px;
  height: 180px;
  background-color: #f5f5f5;
  border: 1px dashed #dcdcdc;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.upload-trigger:hover {
  border-color: #0052d9;
}

.preview-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
}
</style> 